/**
 *
 */
package gemini.basic.dao.impl;

import gemini.basic.dao.GmnDao;
import gemini.basic.dao.MonthlyPointDao;
import gemini.basic.model.AbstractDomain;
import gemini.basic.model.Event;
import gemini.basic.model.MonthlyPoint;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 *
 *
 */
public class MonthlyPointDaoImpl extends HibernateDaoSupport implements MonthlyPointDao {

	private GmnDao gmnDao;

	public void setGmnDao(GmnDao gmnDao) {
		this.gmnDao = gmnDao;
	}

	@Override
	public MonthlyPoint getById(int id) {

		DetachedCriteria dtCri = DetachedCriteria.forClass(MonthlyPoint.class);

		if (id != AbstractDomain.TRANSIENT_ENTITY_ID) {
			dtCri.add(Restrictions.eq("id", id));
		}

		List<Object> monthlyPointList = gmnDao.findByCriteria(dtCri);

		MonthlyPoint result = null;
		
		if (monthlyPointList != null && !monthlyPointList.isEmpty()) {
			result = (MonthlyPoint) monthlyPointList.get(0);
		}
		return result;
	}

	@Override
	public MonthlyPoint saveOrUpdate(MonthlyPoint monthlyPoint, boolean flush) {
		MonthlyPoint result = null;
		if (flush) {
			result = (MonthlyPoint) gmnDao.saveOrUpdateAndFlush(monthlyPoint);
		} else {
			result = (MonthlyPoint) gmnDao.saveOrUpdate(monthlyPoint);
		}
		return result;
	}

	@Override
	public List<MonthlyPoint> getAllMonthlyPointByDistributorId(int id) {
		DetachedCriteria dtCri = DetachedCriteria.forClass(MonthlyPoint.class);
		dtCri.createAlias("distributor", "dis");
		dtCri.add(Restrictions.eq("dis.id", id));

		List<Object> eventList = gmnDao.findByCriteria(dtCri);

		List<MonthlyPoint> result = null;

		if (eventList != null && !eventList.isEmpty()) {
			result = new ArrayList<MonthlyPoint>(eventList.size());
			MonthlyPoint ml = null;
			for (Object ob : eventList) {
				ml = (MonthlyPoint) ob;
				result.add(ml);
			}
		}

		return result;
	}

	@Override
	public List<MonthlyPoint> getMonthlyPointByDistributorCodeAndYear(
			String code, int year) {
		DetachedCriteria dtCri = DetachedCriteria.forClass(MonthlyPoint.class);
		dtCri.createAlias("distributor", "dis");
		dtCri.createAlias("month", "mo");
		dtCri.add(Restrictions.eq("dis.code", code));
		dtCri.add(Restrictions.eq("mo.year", year));

		List<Object> eventList = gmnDao.findByCriteria(dtCri);

		List<MonthlyPoint> result = null;

		if (eventList != null && !eventList.isEmpty()) {
			result = new ArrayList<MonthlyPoint>(eventList.size());
			MonthlyPoint ml = null;
			for (Object ob : eventList) {
				ml = (MonthlyPoint) ob;
				result.add(ml);
			}
		}

		return result;
	}

}
